package com.sk.utility;

import java.io.File;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.sk.cartoonindia.R;
import com.sk.cartoonindia.ShowToonsActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ImageView;

/**
 * @author saurabh
 * Heart of image management for the Gallery
 */
public class ImageSource {
	FileCache fileCache;
	MemoryCache memoryCache = new MemoryCache();
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());
	ExecutorService executorService;
	int targetWidth;
	int targetHeight;

	public ImageSource(Context ctx, int screenWidth, int screenHeight) {

		targetWidth = screenWidth;
		targetHeight = screenHeight;
		fileCache = new FileCache(ctx);
		executorService = Executors.newFixedThreadPool(2);

	}

	final int stub_id = R.drawable.loading;

	public void ShowImage(String url, ImageView imageView) {
		imageViews.put(imageView, url);
		Bitmap bitmap = memoryCache.get(url);
		if (bitmap != null)
			imageView.setImageBitmap(bitmap);
		else {
			queuePhoto(url, imageView);
			imageView.setImageResource(stub_id);
		}
	}

	private void queuePhoto(String url, ImageView imageView) {
		ImageContainer p = new ImageContainer(url, imageView);
		executorService.submit(new PhotosLoader(p));
	}

	class PhotosLoader implements Runnable {
		ImageContainer photoToLoad;

		PhotosLoader(ImageContainer photoToLoad) {
			this.photoToLoad = photoToLoad;
		}

		@Override
		public void run() {
			Log.i("ImageSource", "Thread spawned to get " + photoToLoad.url);
			if (imageViewReused(photoToLoad))
				return;
			Bitmap bmp = getBitmap(photoToLoad.url);
			memoryCache.put(photoToLoad.url, bmp);
			if (imageViewReused(photoToLoad))
				return;
			BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
			try {
				ShowToonsActivity a = (ShowToonsActivity) photoToLoad.imageView
						.getContext();
				a.runOnUiThread(bd);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	boolean imageViewReused(ImageContainer photoToLoad) {
		String tag = imageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.url))
			return true;
		return false;
	}

	private Bitmap getBitmap(String url) {
		File f = fileCache.getFileName(url);

		// from SD cache
		Bitmap b = fileCache.getFile(f, targetWidth);
		if (b != null) {
			Log.i("ImageSource", "Got image from cache(yipee!) " + url);
			return b;
		}
		// from web
		try {
			Bitmap bitmap = null;
			Connection con = new Connection();
			bitmap = con.DownloadBitmap(url);

			fileCache.putFile(url, bitmap);
			Log.i("ImageSource", "Got image from internet " + url);
			bitmap = fileCache.getFile(f, targetWidth);
			return bitmap;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		ImageContainer photoToLoad;

		public BitmapDisplayer(Bitmap b, ImageContainer p) {
			bitmap = b;
			photoToLoad = p;
		}

		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			if (bitmap != null)
				photoToLoad.imageView.setImageBitmap(bitmap);
			else
				photoToLoad.imageView.setImageResource(stub_id);
		}
	}

	public void clearCache() {
		memoryCache.clear();
		fileCache.clear();
	}
}
